import { onMounted, ref, computed, watch } from 'vue'

export default function useCardFrame(props: any, emits: any) {
	const isList = computed(() => props.appList?.length > 0)
	const showStartMask = ref(false)
	const showEndMask = ref(true)
	const activeIndex = ref(0)
	const cardIndex = ref(null)
	const clickFlag = ref(false)
	const popupShow = ref(false)
	const init = () => {
		emits('init')
	}
	const changeCardIndex = (index: any) => {
		cardIndex.value = index
	}
	const changPopupShow = (val: boolean) => {
		popupShow.value = val
	}
	const triggerClick = (index: number) => {
		let list: any = document.getElementById('listContainer')
		list.children[index].click()
	}
	const rollTo = (event: any, index: number) => {
		clickFlag.value = true
		let ele = event.target
		let list: any = document.getElementById('listContainer')
		let part: any = document.getElementById(`part${index}`)
		emits('scrollToPart', part.offsetTop)
		list.scrollTo({
			top: 0,
			left: ele.offsetLeft - (list.clientWidth / 2 - 20),
			behavior: 'smooth',
		})
		activeIndex.value = index

		setTimeout(() => {
			clickFlag.value = false
		}, 500)
	}
	onMounted(() => {
		if (isList.value && !props.title && !props.isSearch) {
			let list: any = document.getElementById('listContainer')
			let contentList: any = document.getElementById('contentList')
			let appListEle: any = document.getElementById('list')
			appListEle.addEventListener('scroll', () => {
				if (!clickFlag.value) {
					Array.prototype.forEach.call(contentList.children, (item, index) => {
						if (item.offsetTop < appListEle.scrollTop + 47) {
							activeIndex.value = index
							list.scrollTo({
								top: 0,
								left:
									list.children[index].offsetLeft - (list.clientWidth / 2 - 20),
								behavior: 'smooth',
							})
						}
					})
				}
			})
			list.addEventListener('scroll', () => {
				showStartMask.value = list.scrollLeft > 5
				showEndMask.value =
					list.scrollWidth - list.scrollLeft - list.clientWidth > 2
			})
		}
	})
	return {
		showStartMask,
		showEndMask,
		rollTo,
		isList,
		activeIndex,
		popupShow,
		changPopupShow,
		triggerClick,
		init,
		cardIndex,
		changeCardIndex,
	}
}
